//
//  File.swift
//  
//
//  Created by Hoa.wang on 2021/10/19.
//

import Foundation
import UIKit

enum NetworkError: Error {
    case decodingError,badRequest
}

class Webservice {
    
    func getAllAds(url: URL, completion: @escaping (Result<[HoaAdModel], NetworkError>) -> Void) {
        
        URLSession.shared.dataTask(with: url) { data, response, error in
            
            guard let data = data, error == nil, (response as? HTTPURLResponse)?.statusCode == 200 else {
                completion(.failure(.badRequest))
                return
            }
            
            if let models = try? JSONDecoder().decode([HoaAdModel].self, from: data) {
                completion(.success(models))
            }
            else {
                completion(.failure(.decodingError))
            }
            
        }.resume()
        
    }
    
    func getImage(url: URL, completion: @escaping (Result<UIImage, NetworkError>) -> Void) {
        
        URLSession.shared.dataTask(with: url) { data, response, error in
            
            guard let data = data, error == nil, (response as? HTTPURLResponse)?.statusCode == 200 else {
                completion(.failure(.badRequest))
                return
            }
            
            if let image = UIImage(data: data) {
                completion(.success(image))
            }
            else {
                completion(.failure(.decodingError))
            }
            
        }.resume()
        
    }
    
}
